package com.chima.action;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;

import org.apache.struts2.ServletActionContext;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;

import com.chima.domain.Department;
import com.chima.domain.DepartmentCoffer;
import com.chima.domain.DetailPost;
import com.chima.domain.Employees;
import com.chima.domain.EmpmoneyModer;
import com.chima.domain.JobDetail;
import com.chima.domain.PageRequestBean;
import com.chima.domain.PageResponseBean;
import com.chima.domain.Performance;
import com.chima.domain.Rate;

import com.chima.domain.HsCheckDepartment;
import com.chima.service.DetailPostService;
import com.chima.service.EmployeeService;
import com.chima.service.JobDetailService;
import com.chima.service.PerformanceCountService;
import com.chima.service.PerformanceService;
import com.chima.service.PostCompetentService;
import com.chima.service.RateService;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import flexjson.JSONSerializer;
import flexjson.transformer.DateTransformer;
public class PerformanceAction extends  ActionSupport implements ModelDriven<Performance>{
   Performance performance=new Performance();
	public Performance getModel() {
		return performance;
	}
	private int start;// 开始页码
	private int flag;// 开始页码
	public int getFlag() {
		return flag;
	}
	public void setFlag(int flag) {
		this.flag = flag;
	}
	private int limit; //每页显示
	private int page;//页数
	private boolean success=false ;
	private String searchdate;
	private int searchdepartment;
    private Double totalReward;
	private PerformanceService performanceService ;
	private DetailPostService detailPostService ;
	private PerformanceCountService performanceCountService ;
	private EmployeeService employeeService ;
	private PostCompetentService postCompetentService ;
	private RateService rateService;
	private JobDetailService jobDetailService ;
	private List<Performance> performances;
	private int sercherdepart;
	private String searchdate1;
	private String searchValue;//查询重新加载条件
	private int searchdepart;//查询重新加载条件
	private Double baifenbi;
	private int []ids;
	private Double []actualrewards;
	
	
	public void setRateService(RateService rateService) {
		this.rateService = rateService;
	}
	public int[] getIds() {
		return ids;
	}
	public void setIds(int[] ids) {
		this.ids = ids;
	}
	public Double[] getActualrewards() {
		return actualrewards;
	}
	public void setActualrewards(Double[] actualrewards) {
		this.actualrewards = actualrewards;
	}
	public void setPostCompetentService(PostCompetentService postCompetentService) {
		this.postCompetentService = postCompetentService;
	}
	public int getSercherdepart() {
		return sercherdepart;
	}
	public void setSercherdepart(int sercherdepart) {
		this.sercherdepart = sercherdepart;
	}
	public void setSearchdepart(int searchdepart) {
		this.searchdepart = searchdepart;
	}
public void setDetailPostService(DetailPostService detailPostService) {
		this.detailPostService = detailPostService;
	}
public Double getBaifenbi() {
		return baifenbi;
	}
	public void setBaifenbi(Double baifenbi) {
		this.baifenbi = baifenbi;
	}
public Double getTotalReward() {
		return totalReward;
	}
	public void setTotalReward(Double totalReward) {
		this.totalReward = totalReward;
	}
public PerformanceCountService getPerformanceCountService() {
		return performanceCountService;
	}
	public void setPerformanceCountService(
			PerformanceCountService performanceCountService) {
		this.performanceCountService = performanceCountService;
	}

public int getSearchdepartment() {
		return searchdepartment;
	}
	public void setSearchdepartment(int searchdepartment) {
		this.searchdepartment = searchdepartment;
	}

public String getSearchValue() {
		return searchValue;
	}
	public void setSearchValue(String searchValue) {
		this.searchValue = searchValue;
	}

	public String getSearchdate1() {
		return searchdate1;
	}
	public void setSearchdate1(String searchdate1) {
		this.searchdate1 = searchdate1;
	}


public EmployeeService getEmployeeService() {
		return employeeService;
	}
	public void setEmployeeService(EmployeeService employeeService) {
		this.employeeService = employeeService;
	}
public String getSearchdate() {
		return searchdate;
	}
	public void setSearchdate(String searchdate) {
		this.searchdate = searchdate;
	}
public JobDetailService getJobDetailService() {
		return jobDetailService;
	}
	public void setJobDetailService(JobDetailService jobDetailService) {
		this.jobDetailService = jobDetailService;
	}
public void setPerformanceService(PerformanceService performanceService) {
		this.performanceService = performanceService;
	}
public int getStart() {
		return start;
	}
	public void setStart(int start) {
		this.start = start;
	}

	public int getLimit() {
		return limit;
	}

	public void setLimit(int limit) {
		this.limit = limit;
	}

	public int getPage() {
		return page;
	}

	public void setPage(int page) {
		this.page = page;
	}
	public boolean isSuccess() {
		return success;
	}

	public void setSuccess(boolean success) {
		this.success = success;
	}
/**
 * 计算奖金查页面显示
 * @return
 * @throws Exception
 */
public String  ListPerformance1() throws Exception{
	Employees  emp =(Employees) ServletActionContext.getRequest().getSession().getAttribute("existEmployee");
	PageRequestBean pageRequestBean = new PageRequestBean();
  //封装条件
	DetachedCriteria criteria = DetachedCriteria.forClass(Performance.class);
	if(searchValue!=null&&searchValue.trim().length()>0){
			criteria.add(Restrictions.eq("date",searchValue));
		}
	if(emp.getName().equals("admin") ){
		if(searchdepart!=0){
			criteria.add(Restrictions.eq("department.id",searchdepart));
			pageRequestBean.setDept(searchdepart);
		}
	}else{
		criteria.add(Restrictions.eq("department.id",emp.getDepartment().getId()));
		pageRequestBean.setDept(emp.getDepartment().getId());
	}
	
	pageRequestBean.setCriteria(criteria);
	pageRequestBean.setStart(start);
	pageRequestBean.setLimit(limit);
	pageRequestBean.setPage(page);
	pageRequestBean.setDate(searchValue);
	
	PageResponseBean pageResponseBean = performanceService.findPerformance(pageRequestBean);
	int total=0;
    total =pageResponseBean.getTotal();
    performances =pageResponseBean.getRows();
    JSONSerializer jsonSerializer = new JSONSerializer();
	jsonSerializer.transform(new DateTransformer("yyyy-MM"),Date.class);
	jsonSerializer.exclude("*.class","*.professional","*.department","*.post","*.jobDetails","*.records","*.jobs","jobDetail");
    String resultJson1 = jsonSerializer.deepSerialize(performances);  
    String resultJson2 =jsonSerializer.serialize(total);
    String jsonString = "{total:"+resultJson2.toString()+",performances:"+resultJson1.toString()+"}";
    System.out.print(jsonString);
	ServletActionContext.getResponse().setContentType("text/json;charset=utf-8");
	ServletActionContext.getResponse().getWriter().print(jsonString);
	return NONE;
}
/**
 * 奖金查询页面显示
 * @return
 * @throws Exception
 */
public String  ListMyPerformance() throws Exception{
	Employees  emp =(Employees) ServletActionContext.getRequest().getSession().getAttribute("existEmployee");
	 PageRequestBean pageRequestBean = new PageRequestBean();
		//封装条件
	 DetachedCriteria criteria = DetachedCriteria.forClass(Performance.class);
	 if( searchdate1==null&&sercherdepart==0){
		 
		 // 获得上一个月
		  SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM"); 
	         Calendar   calendar=Calendar.getInstance(); 
	         calendar.setTime(new Date());
	         calendar.set(Calendar.MONTH,calendar.get(Calendar.MONTH)-1); 
	         String date= sdf.format(calendar.getTime());
		 criteria.add(Restrictions.eq("date",date));
	 }
	
//	if(emp!=null && !emp.getName().equals("admin")){
//		if(emp.getDataPermission()!=null){
//			String [] mm=emp.getDataPermission().split(",");
//			Integer[] dd=new Integer [mm.length];
//			for(int i=0;i<mm.length;i++){
//				 dd[i]=Integer.parseInt(mm[i]); 
//			}
//			criteria.add(Restrictions.in("employee.id",dd));
//		}
//		
//	}
	if(sercherdepart!=0){
			criteria.add(Restrictions.eq("department.id",sercherdepart));
		}
	if(searchdate1!=null&&searchdate1.trim().length()>0){
	
		 criteria.add(Restrictions.eq("date",searchdate1));

	}
//	if(emp!=null && !emp.getName().equals("admin")){
//		pageRequestBean.setDept(emp.getDepartment().getId());
//	}
	pageRequestBean.setCriteria(criteria);
	pageRequestBean.setDate(searchdate1);
	pageRequestBean.setDept(sercherdepart);
	pageRequestBean.setStart(start);
	pageRequestBean.setLimit(limit);
	pageRequestBean.setPage(page);
	PageResponseBean pageResponseBean = performanceService.countPerformance(pageRequestBean);
    int total =pageResponseBean.getTotal();
    List<Performance> performances =pageResponseBean.getRows();
    JSONSerializer jsonSerializer = new JSONSerializer();
	jsonSerializer.transform(new DateTransformer("yyyy-MM"),Date.class);
	jsonSerializer.exclude("*.class","*.professional","*.department","*.post","*.jobDetails","*.records","*.jobs","jobDetail");
//    String resultJson =jsonSerializer.serialize(success);
    String resultJson1 = jsonSerializer.deepSerialize(performances);  
    String resultJson2 =jsonSerializer.serialize(total);
    String jsonString = "{total:"+resultJson2.toString()+",performances:"+resultJson1.toString()+"}";
    System.out.print(jsonString);
	ServletActionContext.getResponse().setContentType("text/json;charset=utf-8");
	ServletActionContext.getResponse().getWriter().print(jsonString);
	return NONE;
}
// 计算最大值
	public Double  sortmax(Double[] temp ){
			Arrays.sort(temp); 
		return  temp[temp.length-1];
	}
/**
 * 计算奖金查询功能
 */
	public String ListPerformance() throws Exception{
		Employees  existEmployee =(Employees) ServletActionContext.getRequest().getSession().getAttribute("existEmployee");
		List<Employees> emp;
		List<Performance> performances;
		if(existEmployee.getName().equals("admin")){
			emp=employeeService.findEmployeesByDeparmet(searchdepartment);
			performances=performanceService.findByDateAndDepartment(searchdate.substring(0, 7), searchdepartment);
		}else{
			emp=employeeService.findEmployeesByDeparmet(existEmployee.getDepartment().getId());
			performances=performanceService.findByDateAndDepartment(searchdate.substring(0, 7),existEmployee.getDepartment().getId());
		}
		String date = searchdate.substring(0, 7);
		if(performances.size()==0){
			for(Employees e :emp){
				Performance performance =new Performance();
				performance.setEmployee(e);
				performance.setDate(date);
				performance.setDepartment(e.getDepartment());
				performanceService.savePerformance(performance);
			}
		}
		List<Performance> performances1;
		List<JobDetail> jobDetails1;
		if(existEmployee.getName().equals("admin")){
			performances1=performanceService.findByDateAndDepartment(date, searchdepartment);
//		    jobDetails1=jobDetailService.findByDateAndDepart(searchdate, searchdepartment);
		    jobDetails1=jobDetailService.findByDateAndDepartAndState(searchdate,searchdepartment,"3");
		}else{
			 performances1=performanceService.findByDateAndDepartment(date, existEmployee.getDepartment().getId());
//			 jobDetails1=jobDetailService.findByDateAndDepart(searchdate, existEmployee.getDepartment().getId());
			 jobDetails1=jobDetailService.findByDateAndDepartAndState(searchdate, existEmployee.getDepartment().getId(),"3");
		}

		 Map<Employees,Double[]> map1 = new HashMap();
		 for(JobDetail jobDetail :jobDetails1){
			 if( jobDetail.getJob()==null){
					Double[] temp;
					 temp = map1.get(jobDetail.getEmployee());
					if(temp == null){
						temp =  new Double[11];
						temp[5] =jobDetail.getShu();
					}else if (temp[5] == null){
						temp[5] = jobDetail.getShu();
					}else{
						temp[5] += jobDetail.getShu();
				}
			   map1.put(jobDetail.getEmployee(),temp );
			   continue;
			 } if(jobDetail.getJob().getNanyi()==1){
				Double[] temp;
				 temp = map1.get(jobDetail.getEmployee());
				if(temp == null){
					temp =  new Double[11];
					temp[0] = jobDetail.getActualcore();
					temp[6] = jobDetail.getShu();
				}else if (temp[0] == null){
					temp[0] = jobDetail.getActualcore();
					temp[6] = jobDetail.getShu();
				}else{
					temp[0] += jobDetail.getActualcore();
					temp[6] += jobDetail.getShu();
				}
				map1.put(jobDetail.getEmployee(),temp);
			 }else if (jobDetail.getJob().getNanyi()==2) {
				 Double[] temp;
				 temp = map1.get(jobDetail.getEmployee());
					if(temp == null){
						temp =  new Double[11];
						temp[1] = jobDetail.getActualcore();
						temp[7] = jobDetail.getShu();
					}else if (temp[1] == null){
						temp[7] = jobDetail.getShu();
						temp[1] = jobDetail.getActualcore();
					}else{
						temp[1] += jobDetail.getActualcore();
						temp[7] += jobDetail.getShu();
					}
					map1.put(jobDetail.getEmployee(),temp );
			}else if (jobDetail.getJob().getNanyi()==3) {
				 Double[] temp;
				 temp = map1.get(jobDetail.getEmployee());
				if(temp == null){
					temp =  new Double[11];
					temp[8] = jobDetail.getShu();
					temp[2] = jobDetail.getActualcore();
				}else if (temp[2] == null){
					temp[2] = jobDetail.getActualcore();
					temp[8] = jobDetail.getShu();
				}else{
					temp[2] += jobDetail.getActualcore();
					temp[8] += jobDetail.getShu();
				}
				map1.put(jobDetail.getEmployee(),temp );
			}else if (jobDetail.getJob().getNanyi()==4) {
					Double[] temp;
					 temp = map1.get(jobDetail.getEmployee());
					if(temp == null){
						temp =  new Double[11];
						temp[9] = jobDetail.getShu();
						temp[3] = jobDetail.getActualcore();
					}else if (temp[3] == null){
						temp[3] = jobDetail.getActualcore();
						temp[9] = jobDetail.getShu();
					}else{
						temp[3] += jobDetail.getActualcore();
						temp[9] += jobDetail.getShu();
					}
					map1.put(jobDetail.getEmployee(),temp );
				}
//			 if(jobDetail.getJob().getJobstyle()==1){
//				 Double[] temp;
//				 temp = map1.get(jobDetail.getEmployee());
//				if(temp == null){
//					temp =  new Double[11];
//					temp[4] = jobDetail.getActualcore();
//					temp[10] = jobDetail.getShu();
//				}else if (temp[4] == null){
//					temp[4] = jobDetail.getActualcore();
//					temp[10] = jobDetail.getShu();
//				}else{
//					temp[4] += jobDetail.getActualcore();
//					temp[10] += jobDetail.getShu();
//				}
//				map1.put(jobDetail.getEmployee(),temp ); 
//			 }
		 }
		if(performances1.size()>0){
//			(entry.getValue()[4]==null?0:entry.getValue()[4])  创新分数 entry.getValue()[4],
				for (Map.Entry<Employees, Double[]> entry : map1.entrySet()) {
					Double total=(entry.getValue()[0]==null?0:entry.getValue()[0])+(entry.getValue()[1]==null?0:entry.getValue()[1])+
							(entry.getValue()[2]==null?0:entry.getValue()[2])+(entry.getValue()[3]==null?0:entry.getValue()[3]);
			  performanceService.updateFen(entry.getValue()[5]==null?0:Integer.valueOf(entry.getValue()[5].intValue()),
			 		entry.getValue()[0], entry.getValue()[1], entry.getValue()[2], entry.getValue()[3],total,entry.getKey(),
			 		entry.getValue()[6]==null?0:Integer.valueOf(entry.getValue()[6].intValue()),
			     	entry.getValue()[7]==null?0:Integer.valueOf(entry.getValue()[7].intValue()),
			     	entry.getValue()[8]==null?0:Integer.valueOf(entry.getValue()[8].intValue()),
			     	entry.getValue()[9]==null?0:Integer.valueOf(entry.getValue()[9].intValue()));
			}	
		}
		List<Rate> rates;
		List<DetailPost> detailPosts;
		if(existEmployee.getName().equals("admin")){
			rates=performanceService.findRateByDateAndDepart(searchdate.substring(0, 7), searchdepartment);
	        detailPosts=detailPostService.findByDeptId(searchdepartment);
		}else{
			 rates=performanceService.findRateByDateAndDepart(searchdate.substring(0, 7), existEmployee.getDepartment().getId());
		     detailPosts=detailPostService.findByDeptId(existEmployee.getDepartment().getId());
		}
//			List<Rate> rates=performanceService.findRateByDateAndDepart(searchdate.substring(0, 7), searchdepartment);
//			List<DetailPost> detailPosts=detailPostService.findByDeptId(searchdepartment);
			Map<Employees,Double[]> map = new HashMap();
			for(Rate p :rates){
					for(DetailPost d :detailPosts){ 
					 	 if(d.getEmployee().getId()==p.getEmployee().getId()){
					 		Double[] temp;
						    temp = map.get(p.getEmployee());
							if(temp == null){
								temp =  new Double[1];
								//temp[0]=p.getGrade()*d.getDetailPostCoffe()*(d.getPostHour()/176)*d.getEmployee().getPostCompetent()*d.getEmployee().getPostManager();
								temp[0]=p.getGrade()*d.getSonPost().getCoffe()*(d.getPostHour()/176)*postCompetentService.findCoffer(d.getEmployee())*d.getEmployee().getPostManager();
							}
							else if(temp[0]==null){
							//	temp[0]=p.getGrade()*d.getDetailPostCoffe()*(d.getPostHour()/176)*d.getEmployee().getPostCompetent()*d.getEmployee().getPostManager();
								temp[0]=p.getGrade()*d.getSonPost().getCoffe()*(d.getPostHour()/176)*postCompetentService.findCoffer(d.getEmployee())*d.getEmployee().getPostManager();
							}
							else{
//								temp[0]+= p.getGrade()*d.getDetailPostCoffe()*(d.getPostHour()/176)*d.getEmployee().getPostCompetent()*d.getEmployee().getPostManager();
								temp[0]+= p.getGrade()*d.getSonPost().getCoffe()*(d.getPostHour()/176)*postCompetentService.findCoffer(d.getEmployee())*d.getEmployee().getPostManager();
					 	 }
						 map.put(p.getEmployee(),temp );
				       }
			       }	
			  }
			for(Performance p:performances1){
				for (Map.Entry<Employees, Double[]> entry : map.entrySet()) {
					if(p.getEmployee().getId()==entry.getKey().getId())
					performanceService.updateTotalTime(entry.getValue()[0],p.getId());
				}
			}
			
			this.success=true;
			JSONSerializer jsonSerializer = new JSONSerializer();
	        String resultJson =jsonSerializer.serialize(success);
	        String jsonString = "{success:"+resultJson.toString()+"}";
			ServletActionContext.getResponse().setContentType("text/json;charset=utf-8");
			ServletActionContext.getResponse().getWriter().print(jsonString);
			
		return NONE;   
  }
	/**
	 * 奖金计算功能
	 * @return
	 * @throws Exception
	 */
	public String jisuanPerformance() throws Exception {
		Employees  existEmployee =(Employees) ServletActionContext.getRequest().getSession().getAttribute("existEmployee");
		List<Performance> performances;
		if(existEmployee.getName().equals("admin")){
			performances=performanceService.findByDateAndDepartment(searchdate.substring(0, 7), searchdepartment);
		}else{
			
			performances=performanceService.findByDateAndDepartment(searchdate.substring(0, 7),existEmployee.getDepartment().getId());
		}
//		List<Performance> performances=performanceService.findByDateAndDepartment(searchdate.substring(0, 7), searchdepartment);
			 Double suntotaltime=0.0;
		   	 Double sumtotal=0.00;
		   	 //计算科室总时间和总分数
			    for(Performance p:performances){
			    	if(p.getTotaltTime()!=null){
			    		if(!(null==p.getChengxu())){
			    			if(p.getChengxu()!=0){
			    				Double time=p.getTotaltTime();
					    		suntotaltime+=time;
			    			}
			    		}	
			    	}
			    	 Double  total=p.getTotalCount();
			    	 if(p.getTotalCount()!=null){
			    		 sumtotal+=total ;
			    	 }
			    }
			// 存储 performance
		//  List<Performance> performance =new  ArrayList<Performance>();
	 	    for(Performance p :performances){
	 	       if(!(null==p.getTotaltTime())){
	 	    	  if(p.getTotaltTime()!=0&& null!=p.getChengxu()&&p.getChengxu()!=0){
		 	    		if(null==p.getTotalCount()){
		 	    				double CHXUreward=(p.getTotaltTime()/suntotaltime)*(totalReward*baifenbi/100);
					 	    	p.setCHXUreward(CHXUreward);
					 	    	p.setReward(CHXUreward);
					 	    	p.setActualreward(CHXUreward);
//		 	    			}	
		 	    		}else{
		 	    			if(p.getTotalCount()==0){
		 	    					double CHXUreward=(p.getTotaltTime()/suntotaltime)*(totalReward*baifenbi/100);
						 	    	p.setCHXUreward(CHXUreward);
						 	    	p.setReward(CHXUreward);
						 	   	    p.setActualreward(CHXUreward);
//		 	    				}
		 	    			}else if(p.getTotalCount()!=0){
		 	    				double CHXUreward=(p.getTotaltTime()/suntotaltime)*(totalReward*baifenbi/100);
		 		 	    	  	double xMreward=(p.getTotalCount()/sumtotal)*(totalReward*(1-(baifenbi/100)));
		 			 	    	double totalreward=CHXUreward+xMreward;
		 			 	    	p.setCHXUreward(CHXUreward);
		 			 	    	p.setXMreward(xMreward);
		 			 	    	p.setReward(totalreward);
		 			 	  	    p.setActualreward(totalreward); 
		 	    			}
		 	    		}
		 	    	}
	 	       }else{
				 	      if(!(null==p.getTotalCount())){
				    		    	if(p.getTotalCount()!=0){
				    		    	    double xMreward=(p.getTotalCount()/sumtotal)*(totalReward*(1-(baifenbi/100)));
							 	    	double totalreward=xMreward;
							 	    	p.setXMreward(xMreward);
							 	    	p.setReward(totalreward);	
							 	        p.setActualreward(totalreward);
				    		    	}
				 	    	}
	 	       }
	 		    performanceService.updatePerformance(p);
	 	    }
	    
	    this.success=true;
		JSONSerializer jsonSerializer = new JSONSerializer();
		String resultJson =jsonSerializer.serialize(success);
		String jsonString = "{success:"+resultJson.toString()+"}";
		ServletActionContext.getResponse().setContentType("text/json;charset=utf-8");
		ServletActionContext.getResponse().getWriter().print(jsonString);
		return NONE;
	}
	
	public String  exprtExecle() throws Exception{
		
		ServletActionContext.getResponse().setContentType("text/json;charset=utf-8");
		ServletActionContext.getResponse().getWriter().print("");
		return NONE;
	}
public String  editreward() throws Exception{
	 for(int i=0;i<ids.length;i++){
		 Performance p=performanceService.findById(ids[i]);
		 p.setActualreward(actualrewards[i]);
		 performanceService.updatePerformance(p);
	 }
	 
     this.success=true;
	 JSONSerializer jsonSerializer = new JSONSerializer();
     String resultJson =jsonSerializer.serialize(success);
     String jsonString = "{success:"+resultJson.toString()+"}";
	 ServletActionContext.getResponse().setContentType("text/json;charset=utf-8");
	 ServletActionContext.getResponse().getWriter().print(jsonString);
		return NONE;   
	
	}
/**
 * 
 * 计算普通职工奖金
 * @throws Exception
 */
public String CountEmpPerformance() throws Exception {
	List<EmpmoneyModer> empmoneyModers =new  ArrayList<EmpmoneyModer>();
	
	 double taotalcoffer=0.0;
//	List<Employees > employees=employeeService.findEmpBypositionAndDept(1, searchdepartment);
	 List<Employees > employees=employeeService.findEmployeesByDeparmet(searchdepartment);
	 //科室内有管理系数的人员
	 List<Employees > employeesmanager=employeeService.findEmployeesmangerByDeparmet(searchdepartment);
	Department department=employeeService.finddepartmentByid(searchdepartment);
	DepartmentCoffer dc=employeeService.findDepartmentCofferbydeptname(department.getName());
	double  totalkaoping=employeeService.findtotalkaoping(searchdepartment,searchdate);
	double totalPostCompetent=employeeService.findtotalPostCompetent(searchdepartment,searchdate);
	
	System.out.println("科室中除了主任总的打分=="+totalkaoping);
	for(Employees e:employees){
		double  empcore=0.0;
		EmpmoneyModer empmoneyModer=new EmpmoneyModer();
		empmoneyModer.setDeptid(e.getDepartment().getId());
		empmoneyModer.setDeptname(e.getDepartment().getName());
		empmoneyModer.setEmpid(e.getId());
		empmoneyModer.setEmployees(e);
		empmoneyModer.setDepartment(e.getDepartment());
		empmoneyModer.setEmpname(e.getName());
		Rate rate=rateService.findByEmpAndDate(e, searchdate);
		if (rate!=null) {
			if (e.getPostManager()>0) {
				//科主任
				if (e.getPosition()==2) {
					double a=((e.getPostManager()/dc.getCoffe())*(rate.getActualworkday()/rate.getWorkday()));
					empcore+=a*(100+(e.getPostCompetent()*100));
					System.out.println(e.getPostCompetent()+"管理系数 是=========="+((e.getPostManager()/dc.getCoffe())*(rate.getActualworkday()/rate.getWorkday()))+"========"+empcore);
					taotalcoffer+=empcore;
				}
				else if (e.getPosition()==3) {
					empcore+=e.getPostManager()*1;
					taotalcoffer+=e.getPostManager()*1;
				}else {
					empcore+=((e.getPostManager()/dc.getCoffe())*(rate.getActualworkday()/rate.getWorkday()))*(rate.getGrade()+e.getPostCompetent()*100);
					taotalcoffer+=empcore;
				}
				
				
			}else {
				empcore+=(e.getPostCompetent()*100+rate.getGrade())*1*rate.getActualworkday()/rate.getWorkday();
				//double PostCompetent=postCompetentService.findCoffer(e);
				taotalcoffer+=empcore;
			}
		}
		System.out.println(e.getName()+"====================="+empcore);
		empmoneyModer.setEmpcore(empcore);
		empmoneyModers.add(empmoneyModer);
	}
	System.out.println("科室总分===="+taotalcoffer);
	for (int i = 0; i < empmoneyModers.size(); i++) {
		performanceService.saveOrupdatePerformance(empmoneyModers.get(i).getEmployees(), taotalcoffer,empmoneyModers.get(i).getEmpcore(), searchdate,totalReward);
		
	}
//	for(Employees e:employees){
//		double rate=rateService.findByEmpAndDate(e, searchdate).getGrade();
//		double PostCompetent=postCompetentService.findCoffer(e);
//		double empcoffe=e.getPostManager()*rate*e.getPostcoffe()*PostCompetent;
//		performanceService.saveOrupdatePerformance(e, taotalcoffer,empcoffe, searchdate,totalReward);
//		e.setPostCompetent(PostCompetent);
//		employeeService.updateEmployees(e);
//		
//		
//	}
    this.success=true;
	JSONSerializer jsonSerializer = new JSONSerializer();
	String resultJson =jsonSerializer.serialize(success);
	String jsonString = "{success:"+resultJson.toString()+"}";
	ServletActionContext.getResponse().setContentType("text/json;charset=utf-8");
	ServletActionContext.getResponse().getWriter().print(jsonString);
	return NONE;
}
/**
 * 显示普通职工奖金
 * @return
 * @throws Exception
 */
	public String  ListEMPPerformance() throws Exception{
	
		PageRequestBean pageRequestBean = new PageRequestBean();
	  //封装条件
		DetachedCriteria criteria = DetachedCriteria.forClass(Performance.class);
		if(searchdepart!=0 ){
				criteria.add(Restrictions.eq("department.id",searchdepart));
				pageRequestBean.setDept(searchdepart);
		}
		if(searchdate!=null ){
			criteria.add(Restrictions.eq("date",searchdate));
			pageRequestBean.setDate(searchdate);
		}
		
		pageRequestBean.setCriteria(criteria);
		pageRequestBean.setStart(start);
		pageRequestBean.setLimit(limit);
		pageRequestBean.setPage(page);
		
		PageResponseBean pageResponseBean = performanceService.findEmpPerformance(pageRequestBean);
		int total=0;
	    total =pageResponseBean.getTotal();
	    performances =pageResponseBean.getRows();
	    JSONSerializer jsonSerializer = new JSONSerializer();
	    String resultJson1 = jsonSerializer.deepSerialize(performances);  
	    String resultJson2 =jsonSerializer.serialize(total);
	    String jsonString = "{total:"+resultJson2.toString()+",performances:"+resultJson1.toString()+"}";
		ServletActionContext.getResponse().setContentType("text/json;charset=utf-8");
		ServletActionContext.getResponse().getWriter().print(jsonString);
		return NONE;
	}
	/**
	 * 显示全院普通职工奖金
	 * @return
	 * @throws Exception
	 */
		public String  HSListEMPPerformance() throws Exception{
			performances=performanceService.findallEmpPerformanceBydate(searchdate1);
		    JSONSerializer jsonSerializer = new JSONSerializer();
		    String resultJson1 = jsonSerializer.deepSerialize(performances);  
		    String jsonString = "{performances:"+resultJson1.toString()+"}";
			ServletActionContext.getResponse().setContentType("text/json;charset=utf-8");
			ServletActionContext.getResponse().getWriter().print(jsonString);
			return NONE;
		}
		
		/**
		 * 
		 * 计算普通职工奖金
		 * @throws Exception
		 */
       public String HSCountEmpPerformance() throws Exception {
    	   HttpSession  session = ServletActionContext.getRequest().getSession();
  		System.out.println("HsJS*******************************");
  		StringBuffer sb=new StringBuffer();
  		String aString="";
  			System.out.println("11111111111111111111111111111111111111");
  			List<HsCheckDepartment>  hsCheckDepartments1=employeeService.findHsCheckDepartmentBymonth(searchdate1);
  			List<HsCheckDepartment>  hsCheckDepartments=employeeService.findHsCheckDepartmentBymonthandflag(searchdate1,0);
  			if (hsCheckDepartments.size()==0&&hsCheckDepartments1.size()>0) {
  				employeeService.updateHsCheckDepartmentByMonth(searchdate1);
  				hsCheckDepartments=employeeService.findHsCheckDepartmentBymonthandflag(searchdate1,0);
  			}
  			 if (hsCheckDepartments.size()>0) {
                for (int i = 0; i < hsCheckDepartments.size(); i++) {
              	  int temp=0;
  				   int deptid=hsCheckDepartments.get(i).getDeptid();
  					aString=HSsearchEmployeesFinanceYorN(deptid,searchdate1);
  				   if(aString.length()>3){
  					   sb.append(hsCheckDepartments.get(i).getDeptname()+"-");
  				   }else {
  					 System.out.println("可以进行ok！！！");
  				     List<Performance>  eModes= this.hsstatisticsEmployeesFinance(deptid,hsCheckDepartments.get(i).getDeptname(),searchdate1);
  				     if ( eModes.size()>0) {
  				    	 hsCheckDepartments.get(i).setFlag(1);
  					}else {
  						hsCheckDepartments.get(i).setFlag(0);
  					 }
  					 for (int j = 0; j < eModes.size(); j++) {
  						
  					    if (temp==0) {
  					    	employeeService.deleteEmpMoneyBydeptidAndDate(deptid,searchdate1);	
  								temp++;
  							}
  							
  					      employeeService.saveorupdateEmpmoney(eModes.get(j));
  							
  					} 
  				}
  				 employeeService.addorupdateHsCheckDepartment(hsCheckDepartments.get(i)); 
                  }
  			}else {
  			  List<Department > departments=employeeService.finddepartmentByflag1(1);
  				System.out.println("22222222222222221111111111111111111111111111111111222222222222222221111");
  				for (int i = 0; i < departments.size(); i++) {
  					
  					HsCheckDepartment hsCheckDepartment=new HsCheckDepartment();
  					hsCheckDepartment.setDeptname(departments.get(i).getName());
  					hsCheckDepartment.setDeptid(departments.get(i).getId());
  					hsCheckDepartment.setMonthdate(searchdate1);
  					int temp=0;
  					   int deptid=departments.get(i).getId();
  						aString=HSsearchEmployeesFinanceYorN(deptid,searchdate1);
  					   if(aString.length()>3){
  						   hsCheckDepartment.setFlag(0);
  						   sb.append(departments.get(i).getName()+"-");
  					   }else {
  						 System.out.println("可以进行ok！！！");
  						 List<Performance>  eModes= this.hsstatisticsEmployeesFinance(deptid,departments.get(i).getName(),searchdate1);
  					     if ( eModes.size()>0) {
  					    	   hsCheckDepartment.setFlag(1);
  						}else {
  							   hsCheckDepartment.setFlag(0);
  						}
  						 for (int j = 0; j < eModes.size(); j++) {
  							
  						    if (temp==0) {
  						    	employeeService.deleteEmpMoneyBydeptidAndDate(deptid,searchdate1);	
  									temp++;
  								}
  								
  						  employeeService.saveorupdateEmpmoney(eModes.get(j));
  								
  						} 
  					}
  					 employeeService.addorupdateHsCheckDepartment(hsCheckDepartment);
  				}
  			}
  			
  			
  		
  		
  		  if (sb.toString().length()>3) {
  			success=false;
  		  }else {
  			success=true;
  			
  		 }
  		   System.out.println(aString+"=================success=============="+success);
  		   JSONSerializer jsonSerializer = new JSONSerializer();
  	       String resultJson1 = jsonSerializer.serialize(success);
  	       String resultJson = jsonSerializer.serialize(sb.toString()); 
  	       String jsonString = "{success:"+resultJson1.toString()+", msg:"+resultJson.toString()+"}";
  	       System.out.println(jsonString);
  		   ServletActionContext.getResponse().setContentType("text/json;charset=utf-8");
  		   ServletActionContext.getResponse().getWriter().print(jsonString);
  		return NONE;

		}
		private List<Performance> hsstatisticsEmployeesFinance(int deptid,
				String deptname, String searchdate12) {
			System.out.println("计算的部分");
			List<Performance> performances=new  ArrayList<Performance>();
			double taotalcoffer=0.0;
			totalReward=employeeService.findtotalRewardbydateanddeptname(searchdate12,deptname);
			
			List<Employees > employees=employeeService.findEmployeesByDeparmet(deptid);
			for(Employees e:employees){
				double rate=rateService.findByEmpAndDate(e, searchdate12).getGrade();
				double PostCompetent=postCompetentService.findCoffer(e);
				taotalcoffer+=e.getPostcoffe()*e.getPostManager()*PostCompetent*rate;
			}
			for(Employees e:employees){
				double rate=rateService.findByEmpAndDate(e, searchdate12).getGrade();
				double PostCompetent=postCompetentService.findCoffer(e);
				double empcoffe=e.getPostManager()*rate*e.getPostcoffe()*PostCompetent;
				Performance pp=new Performance();
				pp.setEmployee(e);
				pp.setDepartment(e.getDepartment());
				pp.setDate(searchdate12);
				pp.setReward(empcoffe/taotalcoffer*totalReward);
				performances.add(pp);
				//performanceService.saveOrupdatePerformance(e, taotalcoffer,empcoffe, searchdate,totalReward);
				e.setPostCompetent(PostCompetent);
				employeeService.updateEmployees(e);
				
				
			}
		
			return performances;
		}
		private String HSsearchEmployeesFinanceYorN(int deptid,
				String searchdate12) {
			String a="";
			System.out.println(deptid+"。。。。。。。。。searchEmployeesFinanceYorN。。。。。。***"+searchdate1);
			int num =employeeService.findrates(deptid,searchdate1);
			
			if (num==0) {
				a="此科室考评没有录入！";
			}
			
			return a;
	    	   
		}  
				
				

		
}
